package org.example.Server.Impl;

import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.Exception.StudentExistException;
import org.example.Mapper.ClazzMapper;
import org.example.Pojo.Clazz;
import org.example.Server.ClazzServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ClazzServerImpl implements ClazzServer {

    @Autowired
    private ClazzMapper clazzMapper;

    /*
    * 根据条件查询班级
    * */
    @Override
    public List<Clazz> getClazz(String name, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Clazz> list=clazzMapper.getClazz(name,begin,end) ;
        for (Clazz clazz : list) {
            LocalDate endDate = clazz.getEndDate();
            if(endDate.isBefore(LocalDate.now())) {
                clazz.setStatus("已结课");
            }else if(endDate.isAfter(LocalDate.now())) {
                clazz.setStatus("未开班");
            }else{
                clazz.setStatus("在读中");
            }
        }
        return list;
    }

    /*
    * 添加班级
    * */
    @Transactional
    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
    }

    /*
    * 根据Id查询班级信息
    * */
    @Override
    public Clazz getClazzById(Integer id) {
        return clazzMapper.getClazzById(id);
    }

    /*
    * 更新班级信息
    * */
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    /*
    * 根据ID删除班级
    * */
    @Transactional
    @Override
    public void delete(Integer id) throws StudentExistException {
        Clazz clazz = clazzMapper.getClazzById(id);
        LocalDate endDate = clazz.getEndDate();
        if(endDate.isBefore(LocalDate.now())) {
            log.info("班级结束时间在现在时间之前，意味这班级中没有有人，就执行删除");
            clazzMapper.delete(id);
        }else {
            log.info("班级中还有人不能删除");
            throw new StudentExistException();
        }
    }

    @Override
    public List<Clazz> getAllClazz() {
        return clazzMapper.getAllClazz();
    }
}
